<template>
  <view>
    <u-navbar :title="$t('information.PostInfo')" :autoBack="false" @leftClick="leftClick(urlIndex)" bgColor="#F6F6F6"
      titleStyle="font-weight: 500; color: #000000;" :placeholder="true">
    </u-navbar>
    <view class="released-view">
			<view class="write-view" style="margin-top: 0;">
        <view class="write-detail">
          <view class="title">{{ $t('information.Category') }}</view>
          <view class="choose-box" @click="labelShow = true">
						<view class="title omit" v-if="formData.categoryId">{{ getTagName() }}</view>
          	<view class="title placeholder" v-else>{{ $t("feeServices.PleaseChoose") }}</view>
            <view class="iconfont icon-jiantou-you you"></view>
          </view>
        </view>
        <view class="write-detail">
          <view class="title">{{ $t('information.ProductName') }}</view>
          <input v-model="formData.title" :placeholder="$t('feeServices.PleaseEnter')" style="flex: 1; text-align: right; font-size: 28upx;" placeholderStyle="color: rgba(0, 0, 0, 0.3); font-size: 28upx;" />
        </view>
      </view>
      <view class="write-view">
        <view class="write-detail">
          <view class="title">{{ $t('information.Location') }}</view>
          <regionSelect ref="regionSelect" :cityValue.sync="cityValue" @countryIosCode="getCurrentPostCity" @totalValue="getTotalValue"></regionSelect>
          <view class="iconfont icon-jiantou-you you" @click="$refs.regionSelect.show = true"></view>
        </view>
        <view class="write-detail">
          <view class="title">{{ $t('information.Price') }}</view>
          <input v-model="formData.price" placeholder="0.00" type="number" style="flex: 1; text-align: right; font-size: 28upx; color: #FE6600;" @blur="formData.price = numberChange(numInput($event.detail.value, 2), 0.01, 1000000)"
            placeholderStyle="color: rgba(0, 0, 0, 0.3); font-size: 28upx;" />
          <view class="title" style="margin-left: 24upx; margin-right: 0upx;">{{ currencyObj.currency }}</view>
        </view>
      </view>
      <view class="Description-view">
        <view class="Description-title">
          <view class="title">{{ $t('information.Description') }}</view>
          <view class="count">{{ formData.description ? formData.description.length : 0 }}/800</view>
        </view>
        <u-textarea v-model="formData.description" :placeholder="$t('information.pleaseEnterDescription')" autoHeight
          maxlength="800" placeholderStyle="color: rgba(0, 0, 0, 0.3)" class="Service-title"
          style="border: unset; padding: 0px;"></u-textarea>
      </view>
      <view class="Description-view">
        <view class="title">{{ $t('dating.UploadCertificate') }}<text style="color: #878787; margin-left: 10upx;">(<text style="color: #61BDB2;">{{ uploadList.length }}</text>/{{ uploadLength }})</text></view>
        <view class="upload-tip">{{ $t('dating.uploadLimitFirst') }}<text class="import">5Mb</text>{{ $t('dating.uploadLimitLast') }}<text class="import">10Mb</text></view>
        <view class="upload-box">
          <view class="pic-box" v-for="(item, index) in uploadList" :key="item.imageUrl" :style="(index + 1) % 3 === 0 ? 'margin-right: 0upx;' : ''">
            <image :src="item.imageUrlCompress" class="pic" mode="aspectFill"></image>
            <view class="delete" @click="uploadList.splice(index, 1)"></view>
          </view>
          <view class="to-upload" v-if="uploadList.length < uploadLength" @click="handleUploadImage"></view>
        </view>
      </view>
      <view class="bond-tip">
        <view>{{ $t('information.bottomTip1') }}<text class="bond-money">{{ currencyObj.symbol }}{{ bondObj.bond }}</text>{{ $t('information.bottomTip2') }}</view>
        <view>{{ $t('information.bottomTip3') }}</view>
      </view>
      <button class="btn" @click="dialogConfirm" :class="{'btn-green': isExit()}">{{ $t("friend.post") }}</button>
    </view>
    <!-- 选择标签 -->
    <u-picker :closeOnClickOverlay="true" @close="labelShow = false" :show="labelShow" ref="uPickerLabel" :columns="[tagList]" @confirm="confirmLabel" keyName="labelName"
      @cancel="labelShow = false" :cancelText="$t('cancel')" :confirmText="$t('confirm')"></u-picker>
  </view>
</template>

<script>
import regionSelect from "../friendsInformation/components/regionSelect.vue";
import { queryCountryCurrency } from '@/services/feeServices.js'
import { queryInfoDetail, infoPost, infoPut, queryLabelList, queryInfoBond } from "@/services/information.js"
import config from "@/config/app.config";
import store from "@/store/index";
export default {
  data() {
    return {
      id: "",
      language: "",
      urlIndex: 'InfoRelease',
      formData: {
        categoryId: null,
        images: "",
        compressImages: "",
        place: "",
        title: "",
        currencyId: null,
        country: "",
        countryIosCode: "",
        description: "",
        price: ""
      },
      currencyObj: {},
      bondObj: {},
      cityValue: [],
      tagList: [],
      labelShow: false,
      isPost: false,
      // 上传图片
      uploadList: [],
      uploadLength: 6,
      isUpload: false
    };
  },
  components: { regionSelect },
  methods: {
    // 上传图片
    async handleUploadImage() {
      if (this.isUpload) {
        return uni.showLoading({
          title: this.$t("information.isUploading")
        });
      }
      uni.chooseImage({
        count: 1,
        sourceType: ["camera", "album"],
        success: async (res) => {
          console.log(res);
          if (res.tempFiles[0].size > 5 * 1024 * 1024) {
            uni.showToast({
              title: this.$t("dating.picLimit", {value: 5}),
              icon: "none",
            });
            return
          }
          this.isUpload = true
          uni.showLoading({
            title: this.$t("information.isUploading")
          });
          const result = await this.uploadFilePromise(res.tempFilePaths[0]);
          console.log(result);
          uni.hideLoading();
          this.isUpload = false
          if (this.uploadList.length < this.uploadLength) {
            let urlObj = {
              imageUrl: result.url,
              imageUrlCompress: result.compressImage || result.url
            }
            this.uploadList.push(urlObj)
          }
        },
      });
    },
    //上传路径
    uploadFilePromise(url) {
      console.log(url);
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: config.server + "/app/oss/upload", // 仅为示例，非真实的接口地址
          filePath: url,
          name: "file",
          header: {
            Authorization: `Bearer ${store.state.token}`,
            version: config.version,
          },
          formData: {
            user: "upload",
          },
          success: (res) => {
            const resp = JSON.parse(res.data);
            setTimeout(() => {
              resolve(resp.data);
            }, 1000);
          },
          complete: () => {
            this.isUpload = false
            uni.hideLoading();
          }
        });
      });
    },
    // 切换分类
    confirmLabel(e) {
      this.formData.categoryId = e.value[0].id
      this.labelShow = false;
    },
    // 获取国家码
    async getCurrentPostCity(e) {
      this.formData.countryIosCode = e;
    },
    // 获取地区
    getTotalValue(value) {
      this.formData.place = JSON.stringify(value);
    },
    // 获取详情
    async getMainDetail() {
      const resp = await queryInfoDetail(this.id)
      if (resp.result.code === 200) {
        this.formData = { ...resp.result.data }
        try {
          this.cityValue = resp.result.data.place ? this.getRegionNameList(JSON.parse(resp.result.data.place)) : []
        } catch {
          this.cityValue = []
        }
        this.uploadList = this.formData.informationImages
        this.$nextTick(() => {
          this.$refs.regionSelect.init(this.cityValue);
        });
      }
    },
    // 表单重置
    dialogFormRest() {
      this.uploadList = []
      this.cityValue = []
      this.formData = {
        categoryId: null,
        images: "",
        compressImages: "",
        place: "",
        title: "",
        currencyId: null,
        country: "",
        countryIosCode: "",
        description: "",
        price: ""
      }
      this.$nextTick(() => {
        this.$refs.regionSelect.init([]);
      });
    },
    // 修改
    async toChangeInfo() {
      const resp = await infoPut(this.formData)
      if (resp.result.code == 200) {
        uni.showToast({
			    icon: 'none',
			    title: this.$t('feeServices.post-success')
			  })
        setTimeout(() => {
          this.isPost = false
          this.leftClick(this.urlIndex)
        }, 1000)
      } else {
        this.isPost = false
      }
    },
    // 新增
    async toChangePost() {
      const resp = await infoPost(this.formData)
      if (resp.result.code == 200) {
        uni.showToast({
			    icon: 'none',
			    title: this.$t('feeServices.post-success')
			  })
        setTimeout(() => {
          this.isPost = false
          this.leftClick(this.urlIndex)
        }, 1000)
      } else {
        this.isPost = false
      }
    },
    // 确定按钮
    dialogConfirm() {
      if (this.isPost) return
      if (!this.isExit(true)) return
      this.isPost = true
      this.formData.images = ''
      this.formData.compressImages = ''
      this.uploadList.map((item, index) => {
        this.formData.images = this.formData.images + `${item.imageUrl}${index === (this.uploadList.length - 1) ? '' : ','}`
        this.formData.compressImages = this.formData.compressImages + `${item.imageUrlCompress}${index === (this.uploadList.length - 1) ? '' : ','}`
      })
      var ChinaObj = {
        cn: '中国',
        en: 'China',
        ru: 'Китай'
      }
      var RussiaObj = {
        cn: '俄罗斯',
        en: 'Russia',
        ru: 'Российская Федерация'
      }
      this.formData.country = this.formData.country ? this.formData.country : JSON.stringify(this.formData.countryIosCode === 'CN' ? ChinaObj : RussiaObj)
      this.formData.status = 1
      if (this.id) {
        this.toChangeInfo()
      } else {
        this.toChangePost()
      }
    },
    // 判空
    isExit(status) {
      if (!this.formData.categoryId) {
        if (status) {
          uni.showToast({
            icon: 'none',
            title: this.$t('information.categoryId-none')
          })
        }
        return false
      }
      if (!this.formData.title) {
        if (status) {
          uni.showToast({
            icon: 'none',
            title: this.$t('information.title-none')
          })
        }
        return false
      }
      if (!this.formData.place) {
        if (status) {
          uni.showToast({
            icon: 'none',
            title: this.$t('information.place-none')
          })
        }
        return false
      }
      if (!this.formData.price) {
        if (status) {
          uni.showToast({
            icon: 'none',
            title: this.$t('information.price-none')
          })
        }
        return false
      }
      if (!this.formData.description) {
        if (status) {
          uni.showToast({
            icon: 'none',
            title: this.$t('information.description-none')
          })
        }
        return false
      }
      if (!(this.uploadList && this.uploadList.length > 0)) {
        if (status) {
          uni.showToast({
            icon: 'none',
            title: this.$t('information.uploadList-none')
          })
        }
        return false
      }
      return true
    },
    numberChange(e, min, max) {
      const Min = Number(min || 0)
      const Max = Number(max || 0)
      const E = Number(e || 0)
      if (E < Min) {
        return Min
      }
      if (E > Max && Max > 0) {
        return Max
      }
      return e
    },
    numInput (num, precision) {
      if (precision === 0) {
        // 输入纯数字
        num = num.replace(/[^\d]/g, '')
        if (String(num)[1] === '0') {
          num = Number(num)
        }
        return num
      } else {
        num = num.replace(/[^\d.]/g, '')
        if (String(num)[0] === '0' && String(num)[1] !== '.') {
          num = Number(num)
        } else if (String(num)[0] === '.') {
          num = null
        } else {
          if (num.indexOf('.') != num.lastIndexOf('.')) {
            num = String(num).substring(0, num.lastIndexOf('.'))
          }
        }
        if (String(num).indexOf('.') !== -1) {
          num = String(num).substring(0, num.indexOf('.') + precision + 1)
        }
        return num
      }
    },
    // 获取当前货币以及保证金
    async getCurrency() {
      const resp = await queryCountryCurrency()
      if (resp.result.code == 200) {
        this.currencyObj = resp.result.data
        this.formData.currencyId = this.currencyObj.id
        this.getBond()
      }
    },
    async getBond() {
      const resp = await queryInfoBond({
        currencyId: this.currencyObj.id
      })
      if (resp.result.code === 200) {
        this.bondObj = resp.result.data
      }
    },
    // 获取分类
    async getLabelList() {
      const resp = await queryLabelList({
        language: 'zh-Hans'
      })
      if (resp.result.code === 200) {
        this.tagList = resp.result.rows.map(item => {
					item.label = JSON.parse(item.category);
          item.labelName = this.getLabelLangType(item);
          return { ...item };
        })
      }
    },
    // 分类名称
    getLabelLangType(obj) {
      if (this.language === 'zh-Hans') {
        return obj.label.cn
      } else if (this.language === 'en') {
        return obj.label.en
      } else if (this.language === 'ru') {
        return obj.label.ru
      }
    },
    // 切换分类获取名称
    getTagName() {
      if (this.formData.categoryId) {
        let index = this.tagList.findIndex(o => o.id == this.formData.categoryId)
        if (index !== -1) {
          return this.tagList[index].labelName
        }
      }
      return ''
    }
  },
  onLoad(e) {
    this.language = uni.getLocale();
    this.getPrePages(this.urlIndex) // 获取上一个页面的路径已经参数
    this.getLabelList()
    this.getCurrency()
    this.id = e.id
    if (this.id) {
      this.getMainDetail()
    } else {
      this.dialogFormRest()
    }
  },
};
</script>

<style lang="scss" scoped>
::v-deep .Requirements .uni-textarea-textarea {
  height: 180upx;
  color: #000000;
  font-size: 28upx;
}

::v-deep .Service-title .uni-textarea-textarea {
  color: #000000;
  font-size: 28upx;
}

::v-deep .u-textarea__count {
  color: rgba(0, 0, 0, 0.3);
}

.omit {
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  word-wrap: break-word;
  white-space: pre-wrap;
  word-break: break-word;
}

.released-view {
  padding: 30upx;

  .choose-box {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .title {
      font-size: 28upx;
      font-family: Source Han Sans CN;
      font-weight: 400;
      color: #000000;
      margin: 0;
    }

    .placeholder {
      color: rgba(0, 0, 0, 0.3) !important;
    }
  }

  .you {
    color: #a6a6a6;
    margin-left: 24upx;
  }

  .category-view {
    padding: 35upx 30upx;
    background: #ffffff;
    border-radius: 20upx;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .title {
    font-size: 28upx;
    font-weight: 400;
    color: #000000;
		margin-right: 20upx;
  }

  .bond-tip {
    width: 100%;
    font-size: 28upx;
    font-family: Source Han Sans CN;
    font-weight: 400;
    color: #878787;
    padding: 70upx 0upx 30upx;
    line-height: 40upx;
    .bond-money {
      color: #FE6600;
      font-weight: bold;
    }
  }

  .Description-view {
    padding: 36upx 20upx;
    background: #ffffff;
    border-radius: 20upx;
    margin-top: 30upx;
    .Description-title {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      white-space: nowrap;
      margin-bottom: 30upx;
      .count {
        font-size: 24upx;
        font-family: HarmonyOS Sans-Regular, HarmonyOS Sans;
        font-weight: 400;
        color: rgba(0,0,0,0.3);
      }
    }
    .upload-tip {
      font-size: 24upx;
      font-family: Source Han Sans CN-Regular, Source Han Sans CN;
      font-weight: 400;
      color: rgba(0,0,0,0.3);
      line-height: 40upx;
      margin-top: 8upx;
      .import {
        color: #61BDB2;
      }
    }
    .upload-box {
      width: 100%;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      .pic-box {
        width: 196upx;
        height: 196upx;
        border-radius: 24upx;
        border: 2upx solid rgba(0,0,0,0.05);
        position: relative;
        margin-right: calc((100% - 200upx * 3) / 2);
        margin-top: 30upx;
        .pic {
          width: 100%;
          height: 100%;
          border-radius: 24upx;
        }
        .delete {
          width: 32upx;
          height: 32upx;
          background-size: 100% 100%;
          background-repeat: no-repeat;
          background-image: url('@/static/image/delete_pic.png');
          position: absolute;
          right: -8upx;
          top: -8upx;
          z-index: 5;
        }
      }
      .to-upload {
        width: 200upx;
        height: 200upx;
        background-size: 100% 100%;
        background-repeat: no-repeat;
        background-image: url('@/static/image/upload_box.png');
        margin-top: 30upx;
      }
    }
  }

  .write-view {
    padding: 0upx 20upx;
    background: #ffffff;
    border-radius: 20upx;
    margin-top: 30upx;

    .write-detail {
      padding: 40upx 0upx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 2upx solid #f6f6f6;
    }
  }

  .btn {
    font-size: 28upx;
    font-weight: 500;
    color: #878787;
    width: 100%;
    height: 90upx;
    background: #e1e1e1;
    border-radius: 20upx;
    text-align: center;
    line-height: 90upx;
  }
  .btn-green {
    background: #61BDB2;
    color: #FFFFFF;
  }
}
uni-button:after {
  border: unset;
}
</style>